package cn.wolfcode.crm.shiro.filter;

import cn.wolfcode.crm.util.JSONUtil;
import cn.wolfcode.crm.util.JsonResult;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;


//需要配置到shiro.xml中去
@Component
public class CRMFormAuthenticationFilter extends FormAuthenticationFilter {

    // 登录成功时调用的方法,返回JSON
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {

        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().println(JSONUtil.toJSONString(new JsonResult()));
        return false;
    }

    // 失败时调用的方法
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        e.printStackTrace();// 打印原始的错误信息
        String msg = "未知错误哦~";
        try {
            if (e instanceof UnknownAccountException){
                msg = "账户不存在";
            }else if (e instanceof IncorrectCredentialsException){
                msg = "账户或密码错误";
            }
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().println(JSONUtil.toJSONString(new JsonResult().mark(msg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}
